import { useEffect, useRef, useState } from 'react'

export function useMounted(callback?: Fn) {
  const [isMounted, setIsMounted] = useState(false)
  // const countRef = useRef(0)

  // fix lint warning
  const cb = useRef(callback)
  cb.current = callback

  useEffect(() => {
    setIsMounted(true)
    const clearEffect = cb.current?.()
    // countRef.current += 1

    return () => {
      console.log(
        '%c --> unmounted, and clear effect...',
        'font-size: 14px; color: purple',
      )
      if (typeof clearEffect === 'function') {
        return clearEffect()
      }
    }
  }, [])

  return isMounted
}
